<?php

	
	include_once("$config[webroot]/includes/page_utf_class.php");
	
	//=================================================
	function creat_table($id)
	{
		global $db,$config;
		$table_name=$config['table_pre']."defind_".$id;
		$csql="
		CREATE TABLE `".$table_name."` (
		  `id` int(11) NOT NULL auto_increment,
		  `info_id` int(11) unsigned default NULL,
		  `info_type` varchar(30) default NULL,
		  `color_img` text default NULL,
		   PRIMARY KEY  (`id`)
		) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ;
		";
		$db->query($csql);
		$sql="ALTER TABLE `$table_name` ADD INDEX ( `info_id`,`info_type` )";
		$db->query($sql);
		
		//----------------------初始默认字段
		//$sql="INSERT INTO `".PROPERTYVALUE."` VALUES ( 0,'color', '颜色', '请选择颜色', 0, '','varchar', '255', 1, 5, '1|红色,2|蓝色', 0, $id, '', 1)";
		//$db->query($sql);
		//----------------------
	}
	
	
	function property_tpl($id,$val){//根据模板设置属性值
		
		global $db,$config;
		

		$sql="select * from ".PROPERTYVALUETEMPATE." where id = $id";
		$db->query($sql);
		$re=$db->fetchRow();
		$str=explode(',',$re['item']);
				$arr=array();
				foreach($str as $v)
				{
					$str1=explode('|',$v);
					if($str1[0]<0){
						$arr[-$str1[0]]=$str1[1];
					}else{
						$arr[$str1[0]]=$str1[1];
					}
				}

				foreach (explode(',',$val) as $key=>$item){
					if($item<0){
						$tmp[]=($item).'|'.$arr[-$item];
					}else{
						$tmp[]=$item.'|'.$arr[$item];
					}
						
				}		
				
				return implode(',',$tmp);
	}
	
	

	if($_POST['act']=="save" || $_POST['act']=="edit")
	{	
		unset($_GET['s']);
		unset($_GET['m']);
		unset($_GET['operation']);
		//添加
		if($_POST["act"]=='save')
		{		
			$sql="insert into ".PROPERTY." (`name`,`create_user`) values ('$_POST[pname]','$_SESSION[ADMIN_USER]')";
			$db->query($sql);
			$id=$db->lastid();

			creat_table($id);
			
			if($_POST['name'])
			{
				foreach($_POST['name'] as $key=>$val)
				{
					$display_type=$_POST["display_type"][$key];
					$is_search=$_POST["is_search"][$key];
					$item1=$_POST["v_item"][$key];
					$statu=$_POST["statu"][$key];
					$field_desc=$_POST["field_desc"][$key];
					$tpl_id=$_POST["tpl_item"][$key];
					
					$num=$_POST["displayorder"][$key]?$_POST["displayorder"][$key]:"0";
					$item = "";
					$arr = "";
					if($val)
					{	
						if($tpl_id&&$item1&&($display_type!=1))
						{
							
							//zx新的模板模式
							/* $item2=explode(',',$item1);
							foreach($item2 as $k=>$v)
							{
								$displayorder=$k+1;
								if($val and $displayorder)
								{
									$arr[]=$displayorder."|".$v;
								}
							}
							$item=implode(',',$arr); */
							$item=property_tpl($tpl_id, $item1);
						}
						$statu=$statu?1:0;
						$sql = "insert into ".PROPERTYVALUE." (`field`,field_name,field_desc,display_type,item,is_search,property_id,status,type,template_id,displayorder,create_user) values ('field','$val','$field_desc','$display_type','$item','$is_search','$id','$statu','1','$tpl_id','$num','$_SESSION[ADMIN_USER]')";
						$db->query($sql);
						$sid=$db->lastid();
						$c[]=$sid;
						$sql = "update ".PROPERTYVALUE." set `field`='s".$sid."' where id='$sid'";
						$db->query($sql);
						
					}
				}
			}
			if($_POST['group'])
			{
				foreach($_POST['group'] as $k=>$v)
				{		
					$item_name=$_POST["item_name"][$k];
					foreach($item_name as $key=>$val)
					{	
						$group=$v[0];
						$item='';
						if($val and $group)
						{							
							$sql = "insert into ".PROPERTYVALUE." (`field`,field_name,field_desc,display_type,item,is_search,property_id,status,type,displayorder,create_user) values ('field','$val','$group','1','','0','$id','1','3','0','$_SESSION[ADMIN_USER]')";
							$db->query($sql);
							$sid=$db->lastid();
							$c[]=$sid;
							$sql = "update ".PROPERTYVALUE." set `field`='p".$sid."' where id='$sid'";
							$db->query($sql);
						}
					}
				}
			}
			if($_POST['stpl_item'])
			{
				foreach($_POST['stpl_item'] as $key=>$val)
				{
						$item=property_tpl($val, $_POST['sv_item'][$key]);
						
						$sql="select * from ".PROPERTYVALUETEMPATE." where id ={$val} limit 1";
						$db->query($sql);
						$list=$db->fetchRow();
						$sql = "insert into ".PROPERTYVALUE." (`field`,field_name,field_desc,display_type,item,is_search,property_id,status,type,template_id,create_user) values ('$list[field]','$list[field_name]','$list[field_desc]','$list[display_type]','$item','$list[is_search]','$id','$list[status]','$list[type]','$list[id]','$_SESSION[ADMIN_USER]')";
						$db->query($sql);
						$table_name=$config['table_pre']."defind_".$id;
						$sql="ALTER TABLE `".$table_name."` ADD `$list[field]` VARCHAR(255) NULL";
						$db->query($sql);
				}
			}
			if($c)
			{
				$str=implode(',',$c);
				$sql="select field from ".PROPERTYVALUE." where id in ($str)";
				$db->query($sql);
				$re=$db->getRows();
				$table_name=$config['table_pre']."defind_".$id;
				foreach($re as $list)
				{
					$sql="ALTER TABLE `".$table_name."` ADD `$list[field]` VARCHAR(255) NULL";
					$db->query($sql);
				}
			}
			if(!empty($_POST['is_search']))
			{	
				 //@todo://为可搜索项增加索引
				
				//$sql2="ALTER TABLE `".$table_name."` ADD INDEX ( `$_POST[field]` )";
				//$db->query($sql2);
			}
		}
		//修改
		if($_POST["act"]=='edit' and is_numeric($_POST['id']))
		{
		
			$id = $_POST['id']*1;
		
			$sql="update ".PROPERTY." set name='$_POST[pname]' where id='$id'";
			$db->query($sql);
					
			$table_name=$config['table_pre']."defind_".$id;
			$a = array();
			$b = array();
			if($_POST['name'])
			{
				$k2=count($_POST['names']);
				foreach($_POST['name'] as $key=>$val)
				{					
					
					
					
					$display_type=$_POST["display_type"][$key+$k2];
					$is_search=$_POST["is_search"][$key+$k2];
					$item1=$_POST["v_item"][$key+$k2];
					$statu=$_POST["statu"][$key+$k2];
					$field_desc=$_POST["field_desc"][$key+$k2];
						
						
					$tpl_id=$_POST["tpl_item"][$key+$k2];
					
					
					$num=$_POST["displayorder"][$key+$k2]?$_POST["displayorder"][$key+$k2]:"0";
					$item = "";
					$arr = "";
					if($val)
					{	
						if($tpl_id&&$item1&&($display_type!=1))
						{
							//zx新的模板模式
							$item=property_tpl($tpl_id, $item1);
						}
						$statu=$statu?1:0;
						
						$sql = "insert into ".PROPERTYVALUE." (`field`,field_name,field_desc,display_type,item,is_search,property_id,status,type,template_id,displayorder,create_user) values ('field','$val','$field_desc','$display_type','$item','$is_search','$id','$statu','1','$tpl_id','$num','$_SESSION[ADMIN_USER]')";
						$db->query($sql);
						$sid=$db->lastid();
						$c[]=$sid;
						$sql = "update ".PROPERTYVALUE." set `field`='s".$sid."' where id='$sid'";
						$db->query($sql);
					}
				}
			}
			if($_POST['pid'])
			{
				foreach($_POST['pid'] as $key=>$val)
				{
					$dd[]=$val;
					$name=$_POST["names"][$key];
					$display_type=$_POST["display_type"][$key];
					$is_search=$_POST["is_search"][$key];
						
					$item1=$_POST["v_item"][$key];
					$statu=$_POST["statu"][$key];
					
					$field_desc=$_POST["field_desc"][$key];
						
					$tpl_id=$_POST["tpl_item"][$key];
						
					$num=$_POST["displayorders"][$key]?$_POST["displayorders"][$key]:"0";
					$item = "";
					$arr = "";
					if($name)
					{
						
						if($tpl_id&&$item1&&($display_type!=1))
						
						{
							//zx新的模板模式
							$item=property_tpl($tpl_id, $item1);
						}
						$statu=$statu?1:0;
						$sql = "update ".PROPERTYVALUE." set `field_name`='$name',`field_desc`='$field_desc',`display_type`='$display_type',`item`='$item',`is_search`='$is_search',`status`='$statu' ,`displayorder`='$num' where id='$val'";
						$db->query($sql);
						if ($display_type==1){
							$sql = "update ".PROPERTYVALUE." set `template_id`='0'  where id='$val'";
							$db->query($sql);
						}
						
						
					}
					else
					{
						$d[]=$val;	
					}
	
				}
				}				
				if($_POST['old_property'])
				{
					$old_property=explode(',',$_POST['old_property']);	
					foreach($old_property as $l)
					{
						if(!in_array($l,(array)$dd))
						{
							$d[]=$l;
						}
					}
				}
		
			
			//zx----------------------------
			unset($dd);
			
			if($_POST['stpl_item']&&$_POST['sv_item']){
				
				
					foreach ($_POST['stpl_item'] as $key=>$item){
						$items=property_tpl($item ,$_POST['sv_item'][$key]);
						
						$dd[]=$_POST['sid_item'][$key];

			    if($items&&$_POST['sid_item'][$key]){
			        
			        $sql = "update ".PROPERTYVALUE." set `item`='".$items."' where id={$_POST['sid_item'][$key]} limit 1";
			        $db->query($sql);
			         
			    }else{
			    	
			    //zx增加原有属性 删除判断 如果原来已有 直接加回
							
						$sql="select id,item from ".PROPERTYVALUE. " where template_id='{$item}' and status<0 and property_id ='{$id}' and type=2 limit 	1";
						
						$db->query($sql);
						if ($rs=$db->fetchRow()){
						
						$tmp1 =$tmp2= array ();
						
						
						foreach (explode(',',$_POST['sv_item'][$key]) as $u1){
							$tmp1[]=$u1>0?$u1:-$u1;
						}
						
						foreach ( explode ( ',',$rs ['item'] ) as $u2 ) {
							$u22 = explode ( '|',$u2 );
							if (!in_array(abs($u22[0]), $tmp1)) {
								$tmp2 [] = (-abs($u22[0])) . '|' . $u22[1];
							}
						}
						
						if ($tmp2){
							$items.=','.implode(',', $tmp2);
						}
						
							$sql = "update ".PROPERTYVALUE." set `item`='".$items."',status=1 where id={$rs['id']} limit 1";
							$db->query($sql);
							unset($items);
							continue;
						}
			    	
			    	
			    	$sql="select * from ".PROPERTYVALUETEMPATE." where id ={$item} limit 1";
			    	$db->query($sql);
			    	$list=$db->fetchRow();
			    	
			    	
			    	
			    	
			    	$sql = "insert into ".PROPERTYVALUE." (`field`,field_name,field_desc,display_type,item,is_search,property_id,status,type,template_id,create_user) values ('$list[field]','$list[field_name]','$list[field_desc]','$list[display_type]','$items','$list[is_search]','$id','$list[status]','$list[type]','$list[id]','$_SESSION[ADMIN_USER]')";
			    	$db->query($sql);
			    	$table_name=$config['table_pre']."defind_".$id;
			    	
			    	if ($list[field]=='color'){
			    		$db->query("ALTER TABLE `$table_name` DROP `color`");
			    	}
			    	
			    	
			    	$sql="ALTER TABLE `".$table_name."` ADD `$list[field]` VARCHAR(255) NULL";
			    	$db->query($sql);
			    	
			    }
			    unset($items);
			    
					}
					
			}
			
			
			
			
			//______________
			
			if($_POST['group'])
			{
				foreach($_POST['group'] as $k=>$v)
				{		
					$item_name=$_POST["item_name"][$k];
					foreach($item_name as $key=>$val)
					{	
						$group=$v[0];
						$item='';
						if($val and $group)
						{							
							$sql = "insert into ".PROPERTYVALUE." (`field`,field_name,field_desc,display_type,item,is_search,property_id,status,type,displayorder,create_user) values ('field','$val','$group','1','','0','$id','1','3','0','$_SESSION[ADMIN_USER]')";
							$db->query($sql);
							$sid=$db->lastid();
							$c[]=$sid;
							$sql = "update ".PROPERTYVALUE." set `field`='p".$sid."' where id='$sid'";
							$db->query($sql);
						}
					}
				}
			}
			if($_POST['groups'])
			{
				foreach($_POST['groups'] as $k=>$v)
				{
					$item_name=$_POST["item_names"][$k];
					foreach($item_name as $key=>$val)
					{	
						$dd[]=$paid=$_POST["paid"][$k][$key];
						$group=$v[0];
						$item='';
						if($val and $group)
						{		
							$sql = "update ".PROPERTYVALUE." set `field_name`='$val' where id='$paid'";
							$db->query($sql);
						}
						else
						{
							$d[]=$paid=$_POST["paid"][$k][$key];
						}
					}
				}				
				if($_POST['old_parameter'])
				{
					$old_parameter=explode(',',$_POST['old_parameter']);	
					foreach($old_parameter as $l)
					{
						if(!in_array($l,$dd))
						{
							$d[]=$l;
						}
					}
				}
			}
			if($_POST['ids'])
			{
			
			
				foreach (explode(',', $_POST['ids']) as $val){
					$spec_id=explode('|', $val);
					
					if(!in_array($spec_id[0],(array)$dd))
						{
							$d[]=$spec_id[0];
						}
					
					
				}
			
			
			/* 
				foreach($_POST['ids'] as $key=>$val)
				{
					$val=substr($val,2,strlen($val)-3);
					$arr=explode(',',$val);	
					$old=$_POST['old_ids'][$key];
					$old_arr=explode(',',$old);	
						
					if($_POST['old_ids'][$key])
					{
						foreach($old_arr as $v)
						{
							if($v)
							{	
								if(!in_array($v,$arr))
								{
									$b[]=$v;	
								}
							}
						}
					}
					foreach($arr as $v)
					{
						if($v)
						{
							if($_POST['old_ids'][$key])
							{
								if(!in_array($v,$old_arr))
								{
									$a[]=$v;	
								}
							}
							else
							{
								$a[]=$v;	
							}
						}
					}
				}
			 */}
/* 			if($a)
			{
				$str=implode(',',$a);
				$sql="select * from ".PROPERTYVALUETEMPATE." where id in ($str)";
				$db->query($sql);
				$re=$db->getRows();
				
				foreach($re as $list)
				{
					$displayorder=$_POST['displayorder'.$list['id'].'']?$_POST['displayorder'.$list['id'].'']:"255";
					$sql = "insert into ".PROPERTYVALUE." (`field`,field_name,field_desc,display_type,item,is_search,property_id,status,type,template_id,displayorder,create_user) values ('$list[field]','$list[field_name]','$list[field_desc]','$list[display_type]','$list[item]','$list[is_search]','$id','$list[status]','$list[type]','$list[id]','$displayorder','$_SESSION[ADMIN_USER]')";
					$db->query($sql);
					if($list['type']!=3 && $list['type']!=4)
					{
						$sql="ALTER TABLE `".$table_name."` ADD `$list[field]` VARCHAR(255) NULL";
						$db->query($sql);
					}
				}
			}
			if($b)
			{
				$str=implode(',',$b);
				$sql="select id,field,type from ".PROPERTYVALUE." where template_id in ($str)";
				$db->query($sql);
				$re=$db->getRows();
				
				foreach($re as $list)
				{
					$sql="select id,field,type from ".PROPERTYVALUE." where field = '$list[field]' ";
					$db->query($sql);
					$s=$db->fetchRow();
				
					if($s['type']!=3 && $s['type']!=4)
					{
						$db->query("ALTER TABLE `$table_name` DROP `$s[field]`");
					}
					$sql="delete from ".PROPERTYVALUE." where id='$s[id]'";
					$db->query($sql);
				}
			} */
			if($c)
			{
				$str=implode(',',$c);
				$sql="select field from ".PROPERTYVALUE." where id in ($str)";
				$db->query($sql);
				$re=$db->getRows();
				foreach($re as $list)
				{
					$sql="ALTER TABLE `".$table_name."` ADD `$list[field]` VARCHAR(255) NULL";
					$db->query($sql);
				}
			}
			if($d)
			{
				$str=implode(',',$d);
				$sql="update ".PROPERTYVALUE ." set status =-1 where id in ($str)";
				$db->query($sql);
				$re=$db->getRows();
				
				/* $str=implode(',',$d);
				$sql="select id,field from ".PROPERTYVALUE." where id in ($str)";
				$db->query($sql);
				$re=$db->getRows();
				foreach($re as $list)
				{
					$db->query("ALTER TABLE `$table_name` DROP `$list[field]`");
					$sql="delete from ".PROPERTYVALUE." where id='$list[id]'";
					$db->query($sql);
				} */
			}
			unset($_GET['editid']);
		}
		$getstr=implode('&',convert($_GET));
		echo "<script>window.parent.main.document.location.reload();window.parent.DialogManager.close('property');</script>";
		msg("?m=product&s=property.php&operation=list&$getstr");
	}
	//信息
	if($_GET['editid'] and is_numeric($_GET['editid']))
	{
		
		$sql="select * from ".PROPERTY." where id='$_GET[editid]'";
		$db->query($sql);
		$de=$db->fetchRow();
		
		$sql="select * from ".PROPERTYVALUE." where property_id='$_GET[editid]' and status>=0 order by status desc, displayorder,id asc";
		$db->query($sql);
		$re=$db->getRows();

		if($re)
		{	
			$cc=$dd=$ee=$ff=array();
			foreach($re as $key=>$val)
			{
				if($val['type']==1)
				{
					$str=explode(',',$val['item']);
					$key_arr=$item_arr=array();
					$cc[]=$val['id'];
					foreach($str as $v)
					{
						$str1=explode('|',$v);
						$key_arr[abs($str1[0])]=$str1[0];
						if ($str1[0]>0){
							$item_arr[$str1[0]]=$str1[1];
						}
					}
					ksort($key_arr);
					ksort($item_arr);	
					$de['value'][$key]=$val;
					$de['value'][$key]['items']=implode(",",$item_arr);
					$de['value'][$key]['keys']=implode(",",$key_arr);
						
					
				}
				else if($val['type']==2)
				{
				    //zx-----------------------
				    if($val['item']){
				        $str=explode(',',$val['item']);
				        $arr=$keysarr=array();
				        foreach($str as $v)
				        {
				            $str1=explode('|',$v);
				            $keysarr[abs($str1[0])]=$str1[0];
				            if ($str1[0]>0){
				            	$arr[$str1[0]]=$str1[1];
				            }
				        }
				        ksort($keysarr);
				        ksort($arr);
				        
				        $val['items']=$arr;
				        
				    }
				    //-------------------------
				    
				    
				    
				    
				    $val['keys']=implode(',',$keysarr);
					$de['spec_list'][$key]=$val;
					$dd[]=$de['spec_list'][$key]['id'].'|'.$de['spec_list'][$key]['template_id'];
					//$de['spec_list'][$key]['id']=$de['spec_list'][$key]['template_id'];
				}
				else if($val['type']==3)
				{
					$bb[]=$val['id'];
					$group=$val['field_desc'];
					$de['parameter_list'][$group][]=$val;
				}
			}
			$de['property']=$cc?implode(",",$cc):"";
			$de['spec']=$dd?implode(",",$dd):"";
			$de['parameter']=$bb?implode(",",$bb):"";
		}
		
	}
	else
	{	
		
		if($_POST['act']=='op')
		{			
			if(is_array($_POST['chk']))
			{
				$id=implode(",",$_POST['chk']);
				
				
				$sql="select 1 FROM ".PCAT." where ext_field_cat in($id)";
				$db->query($sql);
				if($db->getRows()){
					msg("?m=product&s=property.php","您删除的属性组已经绑定分类或产品，请解绑后删除");
				}
				
				$sql="select 1 FROM ".PRO." where property_id in($id) and status>-9";
				$db->query($sql);
				if($db->getRows()){
					msg("?m=product&s=property.php","您删除的属性组已经绑定分类或产品，请解绑后删除");
				}
				
				$sql="delete from ".PROPERTY." where id in ($id)";
				$db->query($sql);
				$sql="delete from ".PROPERTYVALUE." where property_id in ($id)";
				$db->query($sql);
				
				foreach($_POST["chk"] as $val)
				{
					$table_name=$config['table_pre']."defind_".$val;
					$db->query("DROP TABLE `$table_name`");//删除生成的表
					/* $sql="update ".PCAT." set ext_table='0',ext_field_cat='0' where ext_field_cat='$val'";
					$db->query($sql); */
						
				}
				msg("?m=product&s=property.php");
			}									
		}
		
		//===============================================
		if(!empty($_GET['key']))
		{
			$str=" and name like '%$_GET[key]%' ";
		}
		
		$sql="select * from ".PROPERTY." where 1 $str order by id desc";
		$page = new Page;
		$page->listRows=12;
		//分页
		if (!$page->__get('totalRows'))
		{
			$db->query($sql);
			$page->totalRows = $db->num_rows();
		}
		$sql .= "  limit ".$page->firstRow.",".$page->listRows;
		$db->query($sql);
		$de['list']=$db->getRows();
		$de['page']=$page->prompt();
		
	}
	
	$tpl->assign("de",$de);
	$tpl->assign("config",$config);
	$tpl->display("property.htm");

?>
